import { store } from "@/store";
import { defineStore } from "pinia";
import RegionalAgentAPI, {
  type RegionalAgentListQuery,
  type RegionalAgentItemType,
  type RegionalAgentForm,
} from "@/api/user/regionalAgent";

export const useRegionalAgentStore = defineStore("user-regional-agent", () => {
  const list = ref<RegionalAgentItemType[]>([]);

  const totalCount = ref(0);

  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
  });

  async function fetchList(params: RegionalAgentListQuery) {
    loading.list = true;
    const response = await RegionalAgentAPI.getRegionalAgentList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchCreate(data: Partial<RegionalAgentForm>) {
    loading.create = true;
    await RegionalAgentAPI.createRegionalAgent(data);
    loading.create = false;
  }

  async function fetchUpdate(data: Partial<RegionalAgentForm>) {
    loading.update = true;
    await RegionalAgentAPI.updateRegionalAgent(data);
    loading.update = false;
  }

  async function fetchDelete(id: number) {
    loading.delete = true;
    await RegionalAgentAPI.deleteRegionalAgent(id);
    loading.delete = false;
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchList,
    fetchCreate,
    fetchUpdate,
    fetchDelete,
  };
});

export const useRegionalAgentStoreHook = () => {
  return useRegionalAgentStore(store);
};
